package com.training.java.redbox;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.DAOException;
import com.training.java.redbox.domain.Orders;
import com.training.java.redbox.domain.OrdersDAO;
import com.training.java.redbox.domain.OrdersDAOJDBCImpl;

public class FinalCheckoutServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public FinalCheckoutServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Customer customer = (Customer) request.getSession().getAttribute("Customer");
		List<Long> ids = (List<Long>)request.getSession().getAttribute("cart");
		OrdersDAO orderDao = new OrdersDAOJDBCImpl();
		
		
		try{
				long orderNum = orderDao.getOrderNumber();

			for (long id : ids)
			{
				Orders order = new Orders();
				
				order.setStatus("rented");
				order.setCustomer_id(customer.getCustomerId());
				order.setMovie_id(id);
				order.setOrderNumber(orderNum);
		
				orderDao.createOrders(order);
				request.getSession().removeAttribute("cart");
				request.getSession().setAttribute("order", order);
				
				//request.getSession().setAttribute("Rented_Message", "Your order have been submitted.");
				//RequestDispatcher rd= request.getRequestDispatcher("redbox/listMovies");
				//rd.forward(request, response);
				
				//RequestDispatcher rd = request.getRequestDispatcher("/redbox/OrderSummary");
				//rd.forward(request, response);
				
						
				
			}
			
			
			response.sendRedirect("/redbox/OrderSummary");
			
					
			} catch (DAOException e)
			{
				e.printStackTrace();
			}
		
	}

}
